package com.pig.easy.bpm.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * todo:
 *
 * @author : pig
 * @date : 2020/5/16 15:31
 */
@Slf4j
public class BeanUtils {


    /**
     * 转换成 DTO
     *
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T switchToDTO(Object source, Class<T> clazz) {
       return objectToBean(source, clazz);
    }

    /**
     * 将 DTO 转换成 DO
     *
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T switchToDO(Object source, Class<T> clazz) {
        T result = objectToBean(source, clazz);
        setProperty(result, "updateTime", CommonUtils.formatDate(LocalDateTime.now(),CommonUtils.yyyy_MM_ddHHmmss));
        return result;
    }


    /**
     * 功能描述:
     *
     * @param object
     * @param field
     * @param value
     */
    public static final <T> void setProperty(final Object object, final String field, final T value) {
        try {
            for (Method method : object.getClass().getMethods()) {
                if (StringUtils.equals(method.getName(), "set" + StringUtils.capitalize(field))) {
                    method.invoke(object, value);
                    break;
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    public static <T> T objectToBean(Object source, Class<T> clazz) {
        if (source == null) {
            return null;
        }

        try {
            String jsonString = JSON.toJSONString(source);
            return JSON.parseObject(jsonString, clazz);
        } catch (RuntimeException e) {
            log.error("", e);
        }
        return null;
    }

}
